import { type GoGoAST } from "gogocode";
import { CommonParams, IGoGoNodeAttr } from "../../types";
import { updateLocalesFile } from "../../utils/file";
import { hasChinese } from "../../utils/check";

/**
 * 处理属性
 * @param sfcAst SFC的AST
 * @param CONFIG 配置
 * @param logger 日志处理器
 * @param filePath 文件路径
 * @returns AST
 */
const handleAttrs = ({
  sfcAst,
  CONFIG,
  logger,
  filePath,
}: CommonParams & { sfcAst: GoGoAST }): GoGoAST => {
  const { I18N_FUNC, CHINESE_REGEX: CRG } = CONFIG;
  const getKey = (text: string) =>
    updateLocalesFile({
      text,
      CONFIG,
      logger,
      filePath,
    });
  return sfcAst
    .find(`<template></template>`)
    .find(`<$_$ $$$0></$_$>`)
    .each((item) => {
      // 处理属性
      const attrs = item.match["$$$0"] as unknown as IGoGoNodeAttr[];
      attrs.forEach((attr) => {
        const { key, value } = attr;
        if (value && hasChinese(value.content)) {
          const prop = key.content;
          const val = value.content;
          if (/^[A-Za-z][\w-]*$/.test(prop) && !prop.startsWith("v-")) {
            const keyVal = getKey(val);
            value.content = `${CONFIG.I18N_FUNC}('${keyVal}')`;
            key.content = `:${prop}`;
          }
        }
      });
    })
    .root();
};

export default handleAttrs;
